// pages/home/index2.js
import requestUtil from '../../baseRequest'
import urls from '../../requestUrl'
import {
  orderProcess,
  insuranceStatus,
  accidentStatus
} from '../../utils/commons'
import commonUtils from '../../utils/util.js'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    titleImage: urls.baseImagePrefixUrl + "/e6c06858-14cc-4113-a645-2168760e1de5.png",
    underImage: urls.baseImagePrefixUrl + "/7d5d3692-82ee-4230-a790-6817739457b8.png",
    banners:[],
    imagePreFixUrl:urls.baseImagePrefixUrl,
    menuList: [{
      title: '加油优惠',
      icon: '/assets/oiladd.png',
    },{
        title: '运输工单',
        icon: '/assets/yunshu.png',
        url: '/pages/transportConfirm/stepOne/index',
      },
      
      {
        title: '仲裁申诉',
        icon: '/assets/zhongcai.png',
        url: '/pages/arbitration/select/index',
      },

      // {
      //   title: '救援工单',
      //   icon: '/assets/jiuyuan.png',
      //   url: '/pages/workOrder/createOrder/index',
      // },
      {
        title: '拖拖商城',
        icon: '/assets/ttsc.png',
      },
      {
        title: '医疗垫付',
        icon: '/assets/yiliao.png',
        url: '/subpackage/pages/relief/index',
      },
      {
        title: '申诉提交',
        icon: '/assets/shensu.png',
        url: '/subpackage/pages/complaint/add',
      },
      
    ],
    openid: wx.getStorageSync('openid'),
    currentTab: 'tab4',
    tabs: [{
        tabLabel: '我的确认单',
        tabValue: 'tab4'
      },
      {
        tabLabel: '我的医疗救助',
        tabValue: 'tab6'
      },
      {
        tabLabel: '我的申诉单',
        tabValue: 'tab7'
      },
    ],
    spinShow: false,
    orderTags: [{
        value: '-2',
        name: '进行中的工单',
        checked: true,
        color: 'blue'
      },
      {
        value: '-1',
        name: '已完成的工单',
        checked: false,
        color: 'blue'
      }
    ],
    orderCurrentTag: '-2',
    insuranceTags: [{
        name: '进行中',
        checked: true,
        color: 'blue'
      },
      {
        name: '已完成',
        checked: false,
        color: 'blue'
      },
      {
        name: '乘客险',
        checked: true,
        color: 'green'
      },
      {
        name: '货物险',
        checked: false,
        color: 'green'
      }
    ],
    accidentTags: [{
        name: '进行中',
        checked: true,
        color: 'blue'
      },
      {
        name: '已完成',
        checked: false,
        color: 'blue'
      },
      {
        name: '乘客险',
        checked: true,
        color: 'green'
      },
      {
        name: '货物险',
        checked: false,
        color: 'green'
      }
    ],
    taskList: [],
    orderProcess: orderProcess,
    insuranceOrderStatusList: insuranceStatus,
    insuranceList: [],
    accidentList: [],
    orderList: [],
    accidentStatusList: accidentStatus,
    insuranceListQuery: ['4', '6'],
    accidentListQuery: ['0', '1', '2'],
    transportConfirmList: [],
    transportConfirmUrl: {
      "complete": "/pages/transportConfirm/complete/index?id=",
      "detail": "/pages/transportConfirm/detail/index?id="
    },
    arbitrationUrl: '/pages/arbitration/detail/index?id=',
    transportConfirmListCount: 0,
    complaintOrderList: [],
    pageDto: {
      pageSize: 20,
      pageNum: 1,
      total: 0
    }


  },
  handleClickMenuItem(e) {
    this.checkUserInfoRole(() => {
      if (!this.data.openid) {
        this.setData({
          spinShow: true
        })
        setTimeout(() => {
          let openid = getApp().getUserOpenid()
          this.setData({
            openid
          })
          this.handleClickMenuItem(e)
        }, 1000)
      } else {
        this.setData({
          spinShow: false
        })
        const type = e.currentTarget.dataset.type
        let _url = e.currentTarget.dataset.url
        if (type === undefined) {
          wx.navigateTo({
            url: _url
          })
          return;
        }
        let insuranceType = getApp().globalData.insuranceTypes[type].id
        console.log(e)
        const param = {
          openid: this.data.openid,
          classifyId: insuranceType
        };
        requestUtil.postRequest(urls.workOrder.verify, param, (res) => {
          console.log(res)
          if (res) {
            wx.navigateTo({
              url: _url
            })
          } else {
            wx.showModal({
              title: '提示',
              content: '您所属的行业不能购买此服务',
              showCancel: false
            })
          }
        }, () => {})
      }
    })
  },
  handleTabChange({
    detail = {}
  }) {
    console.log('handleTabChange', detail)
    let d = {}
    d.currentTab = detail.key
    this.setData(d)
    if (detail.key == 'tab1' && this.data.orderList.length === 0) {
      this.getWorkOrderList()
    }
    if (detail.key == 'tab2' && this.data.insuranceList.length === 0) {
      this.data.insuranceListQuery = ['4', '6']
      this.getInsuranceOrderList(this.data.insuranceListQuery, '')
    }
    if (detail.key == 'tab3' && this.data.accidentList.length === 0) {
      this.getAccidentReportList()
    }
    if (detail.key == 'tab4' && this.data.transportConfirmList.length === 0) {
      this.getTransportConfirmList(0)
    }
    if (detail.key === 'tab6') {
      this.getRescueApplyOrderList();
    }
    if (detail.key === 'tab7') {
      this.getComplaintOrderList();
    }
    this.setData({
      pageDto: {
        pageSize: 20,
        pageNum: 1,
        total: 0
      }
    })
  },
  getComplaintOrderList() {
    let openid = wx.getStorageSync('openid');
    const formData = {
      openId: openid,
      criteria: {},
      pageDto: {
        ...this.data.pageDto
      }
    };
    if(openid){
      requestUtil.postRequest(urls.complaint.getMiniAppPage, formData, (res) => {
        console.log(res);
        if (!res.hasError) {
          let orderList = [];
          const dataList = res.list;
          for (let i = 0; i < dataList.length; i++) {
            orderList.push({
              ...dataList[i],
              createdDate: commonUtils.formatDate(dataList[i].createdDate, 'yyyy-MM-dd'),
            })
          }
          this.setData({
            complaintOrderList: orderList,
            pageDto: {
              ...this.data.pageDto,
              total: res.total
            }
          })
        }
      })
    }
  },
  showComplaintDetail(event) {
    let orderId = event.currentTarget.dataset.orderid;
    wx.navigateTo({
      url: '/subpackage/pages/complaint/detail?orderId=' + orderId,
    })
  },
  getRescueApplyOrderList() {
    let openid = wx.getStorageSync('openid');
    const formData = {
      openId: openid,
      criteria: {},
      pageDto: {
        pageSize: 99,
        pageNum: 1,
        total: 0
      }
    };
    if(openid){
      requestUtil.postRequest(urls.rescueApply.getPage, formData, (res) => {
        const dataList = res.list;
        if (!res.hasError) {
          let orderList = [];
          for (let i = 0; i < dataList.length; i++) {
            orderList.push({
              ...dataList[i],
              applyDate: commonUtils.formatDate(dataList[i].applyDate, 'yyyy-MM-dd'),
            })
          }
          this.setData({
            orderList,
          })
        }
      })
    }
  },
  showDetail(event) {
    let orderId = event.currentTarget.dataset.orderid;
    wx.navigateTo({
      url: '/subpackage/pages/relief/detail?orderId=' + orderId,
    })
  },
  /**
   * 监听切换工单标签
   */
  onOrderTagChange(event) {
    console.log('!!!!!', event.detail.index)
    this.data.orderCurrentTag = event.detail.index === 0 ? '-2' : '-1'
    this.getWorkOrderList()
    return
  },

  /**点击创建工单按钮 */
  // createWorkOrder() {
  //     this.checkUserInfoRole(() => {
  //         wx.navigateTo({
  //             url: '/pages/workOrder/createOrder/index'
  //         })
  //     })
  // },
  /**点击运输责任单按钮 */
  createTransportConfirm() {
    this.checkUserInfoRole(() => {
      wx.navigateTo({
        url: '/pages/transportConfirm/stepOne/index'
      })
    })
  },
  /**点击运输责任单按钮 */
  createArbitration() {
    this.checkUserInfoRole(() => {
      wx.navigateTo({
        //url: '/pages/arbitration/create/index'
        url: '/pages/arbitration/detail/index?id=3b257a3000354b94b810443169001ed9'
      })
    })
  },
  /**权限拦截 */
  checkUserInfoRole(callback) {
    if (!this.data.userInfo) {
      setTimeout(() => {
        this.getUserInfo();
        this.checkUserInfoRole(callback);
      }, 100)
    } else {
      let userInfo = getApp().globalData.userInfo;
      this.setData({
        userInfo,
      })
      console.log({
        'userInfo': this.data.userInfo
      })
      if (this.data.userInfo) {
        const {
          userInfo
        } = this.data;
        if (userInfo.isMember && parseInt(userInfo.isMember) === 0) {
          //未获取微信授权的情况
          wx.showModal({
            title: '温馨提示',
            content: '您还未完成注册，请完成注册后重试',
            confirmText: '前往注册',
            success: res => {
              if (res.confirm) {
                wx.switchTab({
                  url: '/pages/user/personal/index'
                })
              }
            }
          })
        } else if (userInfo.isRegister && parseInt(userInfo.isRegister) === 0) {
          //获取微信授权，但没注册成为注册用户的情况
          wx.showModal({
            title: '温馨提示',
            content: '您还未完成注册，请完成注册后重试',
            confirmText: '前往注册',
            success: res => {
              if (res.confirm) {
                wx.navigateTo({
                  url: '/pages/user/registerUser/index'
                })
              }
            }
          })
        } else if (userInfo.isDriver && parseInt(userInfo.isDriver) === -1) {
          //注册用户完成，但没完成会员信息录入的情况
          wx.showModal({
            title: '温馨提示',
            content: '您还未完成司机认证，请完成认证后重试',
            confirmText: '前往认证',
            success: res => {
              if (res.confirm) {
                wx.navigateTo({
                  url: '/pages/user/memberRegister/before'
                })
              }
            }
          })
        } else {
          callback()
        }
      } else {
        //查询不到信息的情况
        wx.showModal({
          title: '温馨提示',
          content: '您还未完成注册，请完成注册后重试',
          confirmText: '前往注册',
          success: res => {
            if (res.confirm) {
              wx.switchTab({
                url: '/pages/user/personal/index'
              })
            }
          }
        })
      }
    }
  },

  /**获取用户信息 */
  getUserInfo() {
    let userInfo = getApp().globalData.userInfo
    console.log(userInfo)
    this.setData({
      userInfo: userInfo
    })
  },

  /**获取工单列表 */
  getWorkOrderList() {
    if (!this.data.openid) {
      this.setData({
        spinShow: true
      })
      setTimeout(() => {
        let openid = getApp().getUserOpenid()
        this.setData({
          openid
        })
        this.getWorkOrderList()
      }, 1000)
      return
    } else {
      if (this.data.spinShow) {
        this.setData({
          spinShow: false
        })
      }
    }
    let param = {
      "openid": this.data.openid,
      "status": this.data.orderCurrentTag
    }
    requestUtil.postRequest(urls.workOrder.getOrderList + '?currentpage=1&&pagesize=50', param, (res) => {
      console.log(res)
      this.setData({
        orderList: res.list
      })
    }, () => {})
    // this.getInsuranceOrderList(this.data.insuranceListQuery, '')
    // if (this.data.insuranceList.length === 0) {
    // }
    // this.getAccidentReportList(this.data.accidentListQuery, '')
    // this.getAccidentReportList(['3','4', '6'], '')
    // if (this.data.accidentList.length === 0) {
    // }
  },
  /**跳转更多列表 */
  goToOrderList() {
    wx.navigateTo({
      url: '/pages/workOrder/list/index'
    })
  },
  /**
   * 处理工单点击事件
   * @param {*} e
   */
  handleClickWorkOrder(e) {
    let _orderId = e.detail.id
    let _orderSource = e.detail.from
    let _orderNo = e.detail.orderNo
    if (this.data.orderCurrentTag === '-1') {
      //
      wx.navigateTo({
        url: `/pages/workOrder/orderComplete/index?oid=${_orderId}&&from=${_orderSource}&&ono=${_orderNo}`
      })
    } else {
      wx.navigateTo({
        url: '/pages/workOrder/orderProcess/index?orderid=' + _orderId
      })
    }
  },

  /**处理服务订单列表筛选Tab */
  handelInsuranceListTab(e) {
    let index = e.detail.index
    if (index === 0) {
      this.data.insuranceListQuery = ['0', '1', '5']
      this.getInsuranceOrderList(this.data.insuranceListQuery, '')
    } else if (index === 1) {
      this.data.insuranceListQuery = ['4', '6']
      this.getInsuranceOrderList(this.data.insuranceListQuery, '')
    } else {
      this.data.insuranceListQuery = ['7', '8']
      this.getInsuranceOrderList(this.data.insuranceListQuery, '')
    }
  },

  /**获取服务订单列表 */
  getInsuranceOrderList(statusList, insuranceType) {
    if (!this.data.openid) {
      this.setData({
        spinShow: true
      })
      setTimeout(() => {
        let openid = getApp().getUserOpenid()
        this.setData({
          openid
        })
        this.getInsuranceOrderList(statusList, insuranceType)
      }, 1000);
    } else {
      if (this.data.spinShow) {
        this.setData({
          spinShow: false
        })
      }
      let param = {
        "insuranceClassifyId": insuranceType,
        "openid": this.data.openid,
        "orderStatusList": statusList
      }
      requestUtil.postRequest(urls.insurance.listOrder, param, (res) => {
        this.setData({
          insuranceList: res.list
        })
      }, () => {})
    }
  },

  /**处理事故上报列表筛选Tab */
  handelAccidentListTab(e) {
    let index = e.detail.index
    if (index === 0) {
      this.data.accidentListQuery = ['0', '1', '2']
      this.getAccidentReportList(this.data.accidentListQuery, '')
    } else {
      this.data.accidentListQuery = ['3', '4', '6']
      this.getAccidentReportList(this.data.accidentListQuery, '')
    }
  },

  /**获取事故订单列表 */
  getAccidentReportList(statusList, insuranceType) {
    let param = {
      "insuranceClassifyId": insuranceType,
      "openid": this.data.openid,
      "accidentStatusList": statusList
    }
    requestUtil.postRequest(urls.accident.accidentList, param, (res) => {
      res.list.forEach((item) => {
        item.insuranceType = getApp().getInsuranceTypeKey(item.insuranceClassifyId)
      })
      this.setData({
        accidentList: res.list
      })
    }, () => {})
  },
  /**处理服务订单列表筛选Tab */
  handelTransportConfirmListTab(e) {
    let index = e.detail.index
    //console.log('====',index)
    this.getTransportConfirmList(index)
  },
  /**获取我的确认单列表 */
  getTransportConfirmList(status) {
    if (!this.data.openid) {
      this.setData({
        spinShow: true
      })
      setTimeout(() => {
        let openid = getApp().getUserOpenid()
        this.setData({
          openid
        })
        this.getTransportConfirmList(status)
      }, 1000);
    } else {
      if (this.data.spinShow) {
        this.setData({
          spinShow: false
        })
      }
      let param = {
        "openid": this.data.openid,
        "page": this.DEFAULT_PAGE,
        "rows": this.DEFAULT_SIZE
      }
      if (status || status == 1) {
        param.isArbitrate = status
      }
      requestUtil.postRequest(urls.transportConfirm.list, param, (res) => {
        this.setData({
          transportConfirmList: res.list,
          transportConfirmListCount: res.total
        })
      }, () => {})
    }
  },
  /**跳转更多列表 */
  goToTransportList() {
    wx.navigateTo({
      url: '/pages/transportConfirm/list/index'
    })
  },
  toNewRegister() {
    if (!this.data.userInfo || this.data.userInfo.isMember == 0) {
      wx.navigateTo({
        url: '/subpackage/pages/userRegisterV2/index',
      })
    }
  },
  getBanners(){
    requestUtil.getRequest(urls.article.getBanners,{}, (res) => {
      if(!res.hasError){
        if(res.result && res.result.length>0){
          this.setData({
            banners:res.result,
          })
        }
      }
    })
  },
  toArticleDetail(event){
    let id = event.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/article/detail?id='+id,
    })

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.error(options)
    //获取分销码并全局缓存
    let _distributeCode = options.scene || ''
    getApp().saveDistributeCode(_distributeCode)
    console.log('_distributeCode', _distributeCode)
    console.log('options', options);
    this.getBanners();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.checkUserInfoRole(() => this.getUserInfo());
    switch (this.data.currentTab) {
      case 'tab1':
        this.getWorkOrderList()
        break;
      case 'tab2':
        this.getInsuranceOrderList(this.data.insuranceListQuery)
        break;
      case 'tab3':
        this.getAccidentReportList(this.data.accidentListQuery)
        break;
      case 'tab4':
        this.getTransportConfirmList(0);
        break;
      case 'tab6':
        this.getRescueApplyOrderList();
        break;
      case 'tab7':
        this.getComplaintOrderList();
        break;
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})